package com.zyw.teacher.login.service.impl;

import com.zyw.teacher.login.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * @Description: 根据登录信息和请求资源对应的角色列表判断是否有权限访问资源
 * @Author: zyw
 * @Date: 2018/12/14
 */
@Component
public class DateAccessDecisionManager implements AccessDecisionManager {

    @Autowired
    private DataBaseFilterInvocationSecurityMetadataSource dataSource;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        boolean hasRole = false;
        List<Role> roles = (List<Role>) authentication.getAuthorities();
        if(roles == null || roles.size() == 0){
            throw new AccessDeniedException("DateAccessDecisionManager.decide Access is denied");
        }
        for(Role role : roles){
            if(configAttributes.contains(role)){
                hasRole = true;
            }
        }
        if(!hasRole){
            throw new AccessDeniedException("DateAccessDecisionManager.decide Access is denied");
        }
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        Collection<ConfigAttribute> configAttributes = dataSource.getAllConfigAttributes();
        return configAttributes.contains(attribute);
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return ConfigAttribute.class.isAssignableFrom(clazz);
    }
}
